﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Threading;
using INTEX.SCHEDULER;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// TBList="ICC_STDMACHINE;ICC_QUERYTB;HRSTAMM;MKRF;AMSTAMM;ABPOS;ICC_ABAX;AMSTAMM;ICC_MKRF;ICC_PVKPOS;ICC_JWYARN;ABFOLGE;";//ITXAPS
    /// </summary>
    public partial class ITXAPS : DocumentBase
    {
        #region-------------Properties-----------------------
        string lastDen = "8";
        string SType = "";//排产类型；
        JobView Lastjob;
        ITXEXRPT ITXEXRPT;
        public ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }

        public ITXSSPA Scheduler = new ITXSSPA();

        private readonly TaskScheduler _sync = TaskScheduler.FromCurrentSynchronizationContext();
        private NameScope pagescope = new System.Windows.NameScope();
        int year = 0, month = 0, day = 0;
        bool FilterByMachineType 
        {
            get
            {
                if (chkMType.IsChecked == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            } 
        }
        ITXAPSData m_Data;
        public SETINTEXDB SetEnv
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetEnv");
            }
        }
        public SETINTEXDB SetVKK
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetVKK");
            }
        }
        public SETINTEXDB SetVKP
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetVKP");
            }
        }
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public SETINTEXDB SetProd
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetProd");
            }
        }
        #region=====vwAMSTAMM=======
        CollectionViewSource vwAMSTAMM
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwAMSTAMM");
            }
        }
        DataRow dwAMSTAMM
        {
            get
            {
                if (vwAMSTAMM.View == null)
                    return null;
                if ((DataRowView)vwAMSTAMM.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwAMSTAMM.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwBMKRF=======
        CollectionViewSource vwBMKRF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwBMKRF");
            }
        }
        DataRow dwBMKRF
        {
            get
            {
                if (vwBMKRF.View == null)
                    return null;
                if ((DataRowView)vwBMKRF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwBMKRF.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwBMKRF=======
        CollectionViewSource vwMRILI
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwMRILI");
            }
        }
        DataRow dwMRILI
        {
            get
            {
                if (vwMRILI.View == null)
                    return null;
                if ((DataRowView)vwMRILI.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwMRILI.View.CurrentItem).Row;
            }
        }
        #endregion

        BindingListCollectionView cvMRili
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgMRili.ItemsSource);
            }
        }     BindingListCollectionView cvABP
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgABP.ItemsSource);
            }
        }
             BindingListCollectionView cvSMKRF
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgSABP.ItemsSource);
            }
        }
        BindingListCollectionView cvMachine
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgMachine.ItemsSource);
            }
        }
        
        string KRS
        {
            get
            {
                return m_Data.Right("  " + txtABPAUFKRS.Text.ToString().Trim(), 2);
            }
            set
            {
                txtABPAUFKRS.Text = value;
            }
        }
        string LFD
        {
            get
            {
                return m_Data.Right("000000" + txtABPAUFLFD.Text.ToString().Trim(), 6); ;
            }
            set
            {
                txtABPAUFLFD.Text = value;
            }
        }
        string POS
        {
            get
            {
                return m_Data.Right("000" + txtABPAUFPOS.Text.ToString().Trim(), 3); ;
            }
            set
            {
                txtABPAUFPOS.Text = value;
            }
        }
        string MKFTP
        {
            get
            {
                return m_Data.Right("0000" + txtABPMKFTP.Text.ToString().Trim(), 4); ;
            }
            set
            {
                txtABPMKFTP.Text = value;
            }
        }
        
        string KSTKRS
        {
            get
            {
                return m_Data.Right("  " + this.txtKSTKRS.Text.ToString().Trim(), 2);
            }
            set
            {
                txtKSTKRS.Text = value;
            }
        }
        string KST
        {
            get
            {
                return m_Data.Right("000000" + this.txtFKST.Text.ToString().Trim(), 4); ;
            }
            set
            {
                txtFKST.Text = value;
            }
        }
        string AGANG
        {
            get
            {
                return m_Data.Left(this.txtAGANG.Text.ToString().PadRight(15), 15);
            }
            set
            {
                txtAGANG.Text = value;
            }
        }
        string machtyp
        {
            get
            {
                return m_Data.Left(this.txtMachTyp.Text.ToString().PadRight(8), 8);
            }
            set
            {
                txtMachTyp.Text = value;
            }
        }

        #endregion
        public ITXAPS()
        {
            InitializeComponent();
            this.Name = "智能排产";
            Density.Text = "8"; 
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            NameScope.SetNameScope(this, pagescope);
            m_Data = new ITXAPSData();
            ITXEXRPT = new ITXEXRPT();
            ITXEXRPT.Root = "C:\\IntexReport";
            ITXEXRPT.strCompany = app.company;
            ITXEXRPT.PrintType = "OpenExcel";
            txtABPAUFKRS.Text = "T2";
            txtABPAUFLFD.Text = "001336";
            txtABPAUFPOS.Text = "002";
            txtMDate.Text = m_Data.date;
            Density.Text = "8";
            cvABP.CustomFilter = "JOBTYPE<>'X'";
            ComboBoxItem item;
            switch (app.company)
            {
                case "YGR":
                    item = new ComboBoxItem();
                    item.Content = "细纱排产";
                    cmbStype.Items.Add(item);
                    cmbStype.Text = "细纱排产";
                    break;
                case "JLT":
                    item = new ComboBoxItem();
                    item.Content = "染缸排产";
                    cmbStype.Items.Add(item);
                    cmbStype.Text = "染缸排产";
                    break;
            }
            cmbStype.Items.MoveCurrentToFirst(); 
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DataSet SResult;
            try
            {
                if (IsLoaded) return;
                IsLoaded = true; 

                vwBMKRF.View.CurrentChanged += vwBMKRF_CurrentChanged;
                vwMRILI.View.CurrentChanged += vwMRILI_CurrentChanged;
                vwAMSTAMM.View.CurrentChanged += vwAMSTAMM_CurrentChanged;
                
              }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;

        }
        public delegate DataSet AsyncRunHandle(object p1 = null, object p2 = null, object p3 = null, object p4 = null, object p5 = null);
        string _sTemp = string.Empty;

        public void AsyncRun(string TaskType, object p1 = null, object p2 = null, object p3 = null, object p4 = null, object p5 = null)
        {
            AsyncRunHandle fHandle = null;
            AsyncCallback callback = null;
            IAsyncResult aResult = null;
            WaitHandle waitHandle = null;
            switch (TaskType)
            {
                case "YGRAPSDB":
                    fHandle = new AsyncRunHandle(Scheduler.YGRAPSDB); 
                    break;
                case "JLTAPSDB":
                    fHandle = new AsyncRunHandle(Scheduler.JLTAPSDB); 
                    break;
                case "StartSchedule":
                    fHandle = new AsyncRunHandle(Scheduler.StartSchedule); 
                    break;
            }
            callback = new AsyncCallback(this.AsyncCallbackImpl);
            aResult = fHandle.BeginInvoke(p1, p2, p3, p4, p5, callback, fHandle);
            waitHandle = aResult.AsyncWaitHandle;
            waitHandle.WaitOne();
        }
        public void AsyncCallbackImpl(IAsyncResult run)
        {
            try
            {
                AsyncRunHandle handle = run.AsyncState as AsyncRunHandle;
                DataSet SResult = handle.EndInvoke(run);
                switch (handle.Method.Name)
                {
                    case "JLTAPSDB":
                    case "YGRAPSDB":
                        Task.Factory.StartNew(() => btnQuery_Click(null, null), new CancellationTokenSource().Token, TaskCreationOptions.None, _sync).Wait();
                        break;
                    case "StartSchedule":
                        Scheduler.SaveTempSchedule(SResult);
                        Task.Factory.StartNew(() => btnQuery_Click(null, null), new CancellationTokenSource().Token, TaskCreationOptions.None, _sync).Wait();
                        break;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            //异步执行更新数据库，
            //完成后，异步执行查询
            if (cmbStype.SelectedIndex == -1)
            {
                MessageBox.Show("请选择排产类型。");
                return;
            }
            AsyncRun(SType, KSTKRS, KST, AGANG);
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                RemoveAllJobs();
                DataSet Result = new DataSet();
                DataRow dwData = SetData.ICC_MKRF.NewRow();
                dwData["ABFMANDANT"] = "00";
                dwData["ABFKSTKRS"] = KSTKRS;
                dwData["ABFKST"] = KST;
                Result = m_Data.BuildData(dwData);                
                SetData.Clear();
                SetData.Merge(Result);
                SetEnv.ICC_MKRF.Clear();
                if (SetData.Tables.Contains("BMKRF"))
                {
                    SetEnv.ICC_MKRF.Merge(SetData.Tables["BMKRF"]);
                }
                 
                Scheduler.PrepareAllJob(SetEnv,false);
                Scheduler.ShowMachine();
                if (vwBMKRF != null)
                {
                    if (vwBMKRF.View != null)
                    {
                        vwBMKRF.View.MoveCurrentToFirst();
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
         
        private void AM_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (dwAMSTAMM == null)
                return;
            Machine machine = (Machine)this.FindName("mx" + dwAMSTAMM["MACHINEID"].ToString());
            if (machine != null)
            {
                FocusMachine(mainViewer, machines, machine);
            }
        }
         
 
        private void tabMS_LostFocus(object sender, RoutedEventArgs e)
        {

        }
        private void btnSplit_Click(object sender, RoutedEventArgs e)
        {
            if (dwBMKRF == null)
            {
                MessageBox.Show("请选择一个任务");
                return;
            }
            if (dwBMKRF["MKFTP"].ToString() != "0000")
            {
                MessageBox.Show("必需从原始记录上拆分");
                return;
            }
            int NNUM = Convert.ToInt16(dwBMKRF["JP50"].ToString());
            NNUM = NNUM + 1;
            dwBMKRF["JP50"] = NNUM;
            //获得最大号，如果已经拆分过，增加一个标志 JP50=次数
            DataRow dwNMRKF = SetEnv.ICC_MKRF.Rows.Add();
            dwNMRKF.ItemArray = dwBMKRF.ItemArray;
            dwNMRKF["ABAID"] = INTEXDBC.GetSeq();
            dwNMRKF["MKFTP"] = Helpers.Helper.Right("0000" + dwBMKRF["JP50"].ToString(), 4);

            double qtybase = 1;
            int MKFSME = Convert.ToInt16(dwBMKRF["MKFSME"].ToString());
            qtybase = Convert.ToDouble(dwBMKRF["MKFSMG" + MKFSME].ToString());
            if (txtSplitQty.Text.ToString().Trim() == "")
                txtSplitQty.Text = "0";
            double qty = Convert.ToDouble(txtSplitQty.Text.ToString()) * 100;
            double ratio = qty / qtybase;
            if (ratio > 0.9)
                return;
            double tNMKSF=0,tMKSF=0;;
            for (int i = 1; i < 9; i++)
            {
                double bqty = Convert.ToDouble(dwBMKRF["MKFSMG" + i].ToString());
                tNMKSF+=Math.Round(bqty* ratio)*0.01;
                tMKSF+=Math.Round(bqty * (1 - ratio))*0.01;
                dwBMKRF["MKFSMG" + i] = Math.Round(bqty * (1 - ratio));
                dwNMRKF["MKFSMG" + i] = Math.Round(bqty* ratio); 
            }
            dwBMKRF["JP05"] = tMKSF;
            dwNMRKF["JP05"] = tNMKSF;
            INTEXDBC.SaveICC_MKRF(dwNMRKF);
            INTEXDBC.SaveICC_MKRF(dwBMKRF);
 
        }
 
        private void btnConfirmSchedule_Click(object sender, RoutedEventArgs e)
        {
            if (dwBMKRF == null)
                return;
            dwBMKRF["SPCONFIRM"] = "YES";
            dwBMKRF["JOBTYPE"] = "C";
            Scheduler.SaveSchedule(dwBMKRF, true);
        }
      
        private void btnSClear_Click(object sender, RoutedEventArgs e)
        {
            //cvSMKRF.CustomFilter = null;
        }
        private void btnSFilter_Click(object sender, RoutedEventArgs e)
        {
            if (txtDate.Text.ToString().Trim() == "")
            {
                MessageBox.Show("请输入截止日期!");
                return;
            }
            string filter = "MKFPLDATV<=" + txtDate.Text.ToString() + "";
            //cvMKRF.CustomFilter = filter;
            DataRow[] rows = SetData.ICC_MKRF.Select(filter);
            if (rows.Length > 0)
            {
                DataTable tb = rows.CopyToDataTable();
                SetEnv.ICC_MKRF.Clear();
                SetEnv.ICC_MKRF.Merge(tb);
            }
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            ITXEXRPT.dsSource = SetEnv; ;
            ITXEXRPT.DocType = "JLTAVDOC";
            ITXEXRPT.strExcelFile = @"JLT\JLTAV37.xls";
            ITXEXRPT.WriteExcelReport();
        }

        private void cmbStype_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataSet SResult =new DataSet();
            try
            {
                ComboBoxItem item = e.AddedItems[0] as ComboBoxItem;
                switch (item.Content.ToString().Trim())
                {
                    case "细纱排产":
                        SType = "YGRAPSDB";
                        KSTKRS = "  ";
                        KST = "0400";
                        AGANG = "XS";
                        machtyp = "XS";
                        break;
                    case "染缸排产":
                        SType = "JLTAPSDB";
                        KSTKRS = "  ";
                        KST = "0210";
                        AGANG = "RS";
                        machtyp = "RSGYG";
                        break;
                }
                m_Data.KSTKRS = KSTKRS;
                m_Data.KST = KST;
                m_Data.AMTYP =Helpers.Helper.Right(machtyp.PadRight(8),8);
                
                SResult = m_Data.LoadEnv();
                SetEnv.Merge(SResult);
              
            }
            catch (Exception ex)
            {
                SetEnv.Clear();
                SetEnv.Merge(SResult);
            }
            finally
            {
                SetupMachine();
                AsyncRun(SType, KSTKRS, KST, AGANG);
            }
        }
      

        private void btnShowExt1_Click(object sender, RoutedEventArgs e)
        {
            if (ZoneExt1.Visibility == Visibility.Collapsed)
            {
                ZoneExt1.Visibility = Visibility.Visible; 
                return;
            }
            if (ZoneExt1.Visibility == Visibility.Visible)
            {
                ZoneExt1.Visibility = Visibility.Collapsed; 
                return;
            }
        }
        private void btnShowExt2_Click(object sender, RoutedEventArgs e)
        {
            if (ZoneExt2.Visibility == Visibility.Collapsed)
            {
                ZoneExt2.Visibility = Visibility.Visible;
                return;
            }
            if (ZoneExt2.Visibility == Visibility.Visible)
            {
                ZoneExt2.Visibility = Visibility.Collapsed;
                return;
            }
        }
        private void btnShowExt3_Click(object sender, RoutedEventArgs e)
        {
            if (ZoneExt3.Visibility == Visibility.Collapsed)
            {
                ZoneExt3.Visibility = Visibility.Visible;
                return;
            }
            if (ZoneExt3.Visibility == Visibility.Visible)
            {
                ZoneExt3.Visibility = Visibility.Collapsed;
                return;
            }
        }

     
        private void MachineManagement_Click(object sender, RoutedEventArgs e)
        {
            MachineManagement.Visibility = Visibility.Visible;
        }

        private void TabItem_GotFocus(object sender, RoutedEventArgs e)
        {
            MachineManagement.Visibility = Visibility.Collapsed;
            ExportManagement.Visibility = Visibility.Collapsed;
        }  
        private void btnExportManagement_Click(object sender, RoutedEventArgs e)
        {
            ExportManagement.Visibility = Visibility.Visible;
        } 
    }
}
